package manager

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/api/admin/internal/model/pg"
	"navi-mumbai/app/api/admin/internal/svc"
	"navi-mumbai/app/api/admin/internal/types"
	"navi-mumbai/common/auth"
	"navi-mumbai/common/ctxdata"
	"navi-mumbai/common/key/idkey"
	"navi-mumbai/common/xerr"

	"github.com/zeromicro/go-zero/core/logx"

	apiAuth "navi-mumbai/app/api/admin/internal/auth"
)

type AddManagerLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddManagerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddManagerLogic {
	return &AddManagerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddManagerLogic) AddManager(req *types.AddManagerReq) (resp *types.AddManagerResp, err error) {
	// verify permission level
	adminUid := ctxdata.GetUidFromCtx(l.ctx)
	level := ctxdata.GetAdminPermissionLevelFromCtx(l.ctx)
	if !l.svcCtx.Auth.VerifyPermissionLevel(l.ctx, apiAuth.SuperAdminAddManagerApi, adminUid, level) {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.AuthFail, "permission denied")
	}

	if req.Uid <= idkey.UidAdminMin || req.Uid >= idkey.UidAdminMax {
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "uid range error")
	}

	// log
	defer func() {
		apiAuth.WriteAdminLog(l.ctx, l.svcCtx.ApiLogModel, adminUid, apiAuth.SuperAdminAddManagerApi, req, resp, err)
	}()

	mg := pg.Manager{
		Uid:             req.Uid,
		Username:        req.Username,
		PermissionLevel: req.PermissionLevel,
		AllowApi:        req.AllowApi,
	}
	var hs []byte
	hs, err = auth.GenerateFromPassword(req.Password)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}

	mg.Userpass = string(hs)

	_, err = l.svcCtx.ManagerModel.Insert(l.ctx, &mg)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	return
}
